<?php
class Pool
{
	private $_storage = array();
	
	public function __construct()
	{
		switch($pid = pcntl_fork())
		{
			case 0:
				Thread::main();
				exit;
			case -1: case false:
				throw new Exception('Cant\' fork new process');
			default:
			{
				$sock = socket_create(AF_UNIX, SOCK_STREAM, 0);
		
				socket_set_nonblock($sock);
				
				$sock_addr = '/tmp/mt.sock';
				
				if(file_exists($sock_addr))
				{
					unlink($sock_addr);
				}
				
				socket_bind($sock, $sock_addr);
				
				socket_listen($sock, 10);
				
				$thread = array();
				
				while(true)
				{
					if($cli = @socket_accept($sock))
					{
						$thread[md5(microtime(true))] = $cli;
					}
					
					if($pid == pcntl_waitpid(-1, $status, WNOHANG))
					{
						break;
					}
					
					foreach($thread as $ndx => $cli)
					{
						if(($data = socket_read($cli, 4096)) !== false)
						{
							if(!$data)
							{
								socket_close($thread[$ndx]);
								unset($thread[$ndx]);
							}
							else
							{
								foreach(explode("\x00", trim($data, "\x00")) as $pack)
								{
									if($pack{0} == "\x01")
									{
										list($name, $value) = unserialize(substr($pack, 1));
										
										$this->_storage[$name] = $value;
									}
									else
									{
										socket_write($cli, serialize(isset($this->_storage[$pack]) ? $this->_storage[$pack] : null) ."\x00");
									}
								}
							}
						}
					}
					
					usleep(1000);
				}
			}
		}
	}
}